package com.tengju.support.infrastructure.repository.resource;

import com.tengju.support.domain.model.resource.Position;
import com.tengju.support.domain.model.resource.Resource;
import com.tengju.support.domain.model.resource.ResourceId;
import com.tengju.support.domain.model.resource.ResourceRepository;
import com.tengju.support.domain.shared.IdObject;
import com.tengju.support.infrastructure.persistence.mybatis.dataobject.AppBannerInfoDO;
import com.tengju.support.infrastructure.persistence.mybatis.mapper.tengju.custom.AppBannerInfoMapper;
import com.tengju.support.infrastructure.repository.resource.convert.ResourceConvert;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
public class ResourceRepositoryImpl implements ResourceRepository {

    @javax.annotation.Resource
    AppBannerInfoMapper appBannerInfoMapper;

    @Override
    public List<Resource> findAll() {
        List<AppBannerInfoDO> appBannerInfoDOList = appBannerInfoMapper.findAll();

        return appBannerInfoDOList.stream().map(ResourceConvert::convertToModel).collect(Collectors.toList());
    }

    @Override
    public Resource find(ResourceId resourceId) {
        AppBannerInfoDO bannerInfoDO = appBannerInfoMapper.findById(resourceId.getValue());
        return ResourceConvert.convertToModel(bannerInfoDO);
    }

    @Override
    public void add(Resource resource) {
        AppBannerInfoDO appBannerInfoDO = ResourceConvert.convertToDO(resource);
        appBannerInfoDO.setCreateTime(LocalDateTime.now());
        appBannerInfoDO.setUpdateTime(LocalDateTime.now());
        appBannerInfoDO.setDeleted(false);
        appBannerInfoMapper.insert(appBannerInfoDO);
    }

    @Override
    public void edit(Resource resource) {
        AppBannerInfoDO appBannerInfoDO = ResourceConvert.convertToDO(resource);
        appBannerInfoMapper.update(appBannerInfoDO);
    }

    @Override
    public void del(ResourceId resourceId) {
        appBannerInfoMapper.delete(resourceId.getValue());
    }

    @Override
    public int count(ResourceId resourceId, String title, List<Position> positions) {
        Long id = Optional.ofNullable(resourceId).map(IdObject::getValue).orElse(null);
        return appBannerInfoMapper.count(id, title, positions);
    }

    @Override
    public List<Resource> queryByPage(ResourceId resourceId, String title, List<Position> positions, Integer offset, Integer pageSize) {
        Long id = Optional.ofNullable(resourceId).map(IdObject::getValue).orElse(null);
        List<AppBannerInfoDO> appBannerInfoDOList = appBannerInfoMapper.queryByPage(id, title, positions, offset, pageSize);
        return appBannerInfoDOList.stream().map(ResourceConvert::convertToModel).collect(Collectors.toList());
    }

    @Override
    public void softDel(ResourceId resourceId) {
        appBannerInfoMapper.softDelete(resourceId.getValue());
    }
}
